<template>
  <div id="main" style="width: 80vw;height:600px;"></div>
</template>
<script>
import * as echarts from "echarts";
import { COLORLIST } from '@/utils/variate'
export default {
  props: {
    // 线形图数据
    lineData: {
      type: Object,
      required: true
    },
    // 添加截取组
    moveingMark: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    lineData: {
      handler(value) {
        this.$nextTick(() => {
          this.setLinsttypeData(value);
        })
      },
      deep: true,
      immediate: true
    },
    moveingMark: {
      handler(value) {
        this.moveingMarkLines = value
        this.$emit('handleChange', this.moveingMarkLines)
        this.initChart();
      },
      deep: true
    }
  },
  data() {
    return {
      myChart: null,
      originData: [],   // 图形数据
      moveingMarkLines: []
      // [
      //   {
      //     id: "L1",
      //     x: 50,
      //     backgroundColor: "rgba(0, 193, 255, 0.2)",
      //     color: "#00b0f0",
      //   },
      //   {
      //     id: "L2",
      //     x: 100,
      //     backgroundColor: "rgba(0, 193, 255, 0.2)",
      //     color: "#00b0f0",
      //   },
      //   {
      //     id: "L3",
      //     x: 200,
      //     backgroundColor: "rgba(9, 128, 23, 0.2)",
      //     color: "#098017",
      //   },
      //   {
      //     id: "L4",
      //     x: 300,
      //     backgroundColor: "rgba(9, 128, 23, 0.2)",
      //     color: "#098017",
      //   },
      // ],
    };
  },
  mounted() {
    this.initChart();
  },
  methods: {
    setLinsttypeData(lines) {
      const maxValue = Math.max(...(Object.values(lines).map(item => item.length)))
      let xAxisList = Array.from({ length: maxValue }, (_, i) => i)
      let result = {}
      for (const k in lines) {
        result[k] = xAxisList.map((item, index) => {
          return [item, lines[k][index]]
        })
      }
      this.originData = result
      this.initChart()
    },
    initChart() {
      const chartDom = document.getElementById("main");
      this.myChart = echarts.init(chartDom);
      let option;

      option = {
        title: {
          text: "操作图形",
          color: "black",
          fontWeight: 600,
          fontSize: 18,
        },
        color: COLORLIST,
        legend: {
          type: 'scroll',
          orient: 'vertical',
          align: 'left',
          right: '20',
          top: '60',
          icon: 'circle',
          width: "80%",
          textStyle: {
            fontSize: 20
          },
        },
        grid: {
          left: '3%',
          right: '13%',
          containLabel: true,
          bottom: 0,
        },
        tooltip: {
          // trigger: 'axis',
          axisPointer: {
            type: "cross",
          },
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          id: "x0",
          type: "value",
          // boundaryGap: false,
          // inverse: true,
          minorTick: {
            show: true,
          },
          axisLine: {
            onZero: false,
          },
          axisTick: {
            show: true,
            inside: true,
          },
          axisLabel: {
            formatter: "{value}",
            textStyle: {
              fontWeight: 700,
              color: "#4c4c4c",
              fontSize: 20,
            },
          },
          splitLine: {
            show: false,
            
          }
        },
        yAxis: {
          id: "y0",
          type: "value",
          minorTick: {
            show: true,
          },
          axisTick: {
            show: true,
            inside: true,
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "black",
            },
          },
          axisLabel: {
            formatter: "{value}",
            textStyle: {
              fontWeight: 700,
              color: "#4c4c4c",
              fontSize: 20,
            },
          },
          splitLine: {
            show: false,
          },
        },
        dataZoom: {
          type: "inside",
          zoomOnMouseWheel: "ctrl",
        },
        // visualMap: {
        //   show: false,
        //   dimension: 0,
        //   pieces: [
        //     {
        //       lte: 6,
        //       color: 'green'
        //     },
        //     {
        //       gt: 6,
        //       lte: 8,
        //       color: 'red'
        //     },
        //     {
        //       gt: 8,
        //       lte: 14,
        //       color: 'green'
        //     },
        //     {
        //       gt: 14,
        //       lte: 17,
        //       color: 'red'
        //     },
        //     {
        //       gt: 17,
        //       color: 'green'
        //     }
        //   ]
        // },
        // series: [
        //   {
        //     name: "Electricity",
        //     type: "line",
        //     smooth: true,
        //     // prettier-ignore
        //     data: [],
        //     // data: [[0, 300], [1, 280], [2,250], [3,260], [4,270], [5,300], [6,550], [7,500], [8,400], [9,390], [10,400], [11,380], [12,390], [13,400], [14,500], [15,600], [16,750], [17,800], [18,700], [19, 400]],
        //     markArea: {
        //       data: this.group(this.moveingMarkLines, 2).map((item) => {
        //         return item.map((i) => {
        //           return {
        //             xAxis: i.x,
        //             name: i.id,
        //             itemStyle: {
        //               color: i.backgroundColor,
        //             },
        //           };
        //         });
        //       }),
        //     },
        //     markLine: {
        //       symbol: "none",
        //       animation: false,
        //       data: this.moveingMarkLines.map((item) => {
        //         return {
        //           name: item.id,
        //           xAxis: item.x,
        //           lineStyle: {
        //             type: "dashed",
        //             width: 3,
        //             color: item.color,
        //           },
        //           label: {
        //             color: item.color,
        //             show: true,
        //             fontSize: 16,
        //             fontWeight: "bolder",
        //           },
        //         };
        //       }),
        //     },
        //   },
        // ],
        servies: []
      };
      const _this = this
      setTimeout(() => {
        const imgItem = this.myChart.getConnectedDataURL({
          pixelRatio: 2,  // 放大二倍下载
          backgroundColor: '#fff',
        })
        _this.$emit('shotImg', imgItem)
      }, 100)

      let serviceData = []
      for (const k in this.originData) {
        serviceData.push({
          name: k,
          type: "line",
          smooth: true,
          symbol: 'none',
          data: this.originData[k],
          lineStyle: { 
            width: 3
          }
        })
      }
      option.series = serviceData
      option.series[0] = {
        ...option.series[0],
        type: 'line',
        markArea: {
          data: this.group(this.moveingMarkLines, 2).map((item) => {
            return item.map((i) => {
              return {
                xAxis: i.x,
                name: i.id,
                label: {
                  color: i.backgroundColor
                },
                itemStyle: {
                  color: i.backgroundColor,
                },
              };
            });
          }),
        },
        markLine: {
          symbol: "none",
          animation: false,
          data: this.moveingMarkLines.map((item) => {
            return {
              name: item.id,
              xAxis: item.x,
              lineStyle: {
                type: "dashed",
                width: 3,
                color: item.color,
              },
              label: {
                color: item.color,
                show: true,
                fontSize: 16,
                fontWeight: "bolder",
              },
            };
          }),
        }
      }
      // this.myChart.setOption({
      //   series: [ serviceData[0] ]
      // })

      let isClick = false;
      let currentId = null;
      this.myChart.on("mousedown", function(params) {
        if (params.componentType === "markLine") {
          // console.log('点击了', params.name)
          currentId = params.name;
          isClick = true;
        }
      });
      // this.myChart.getZr().on('mousemove', (params) => {
      //   if (isClick) {
      //   }
      // })
      this.myChart.getZr().on("mouseup", (params) => {
        if (!isClick) return;
        const pointInGrid = this.myChart.convertFromPixel("grid", [
          params.offsetX,
          params.offsetY,
        ]);
        const currentItem = this.moveingMarkLines.find(
          (item) => item.id === currentId
        );
        currentItem.x = pointInGrid[0];

        const currentService = this.myChart?.getOption()?.series?.[0];
        const markLineList = currentService?.markLine?.data;

        setTimeout(() => {
          this.myChart.setOption({
            series: [
              {
                markArea: {
                  data: this.group(this.moveingMarkLines, 2).map((item) => {
                    return item.map((i) => {
                      if (i.id === currentId) {
                        return {
                          xAxis: currentItem.x,
                          name: i.id,
                          label: {
                            color: i.backgroundColor
                          },
                          itemStyle: {
                            color: i.backgroundColor,
                          },
                        };
                      } else {
                        return {
                          xAxis: i.x,
                          name: i.id,
                          label: {
                            color: i.backgroundColor
                          },
                          itemStyle: {
                            color: i.backgroundColor,
                          },
                        };
                      }
                    });
                  }),
                },
                markLine: {
                  data: markLineList.map((item) => {
                    if (item.name === currentId) {
                      return {
                        ...item,
                        xAxis: currentItem.x,
                        // name: currentId,
                        // lineStyle: {
                        //   type: "dashed",
                        //   width: 3,
                        //   color: '#000'
                        // }
                      };
                    } else {
                      return {
                        ...item,
                      };
                    }
                  }),
                },
              },
            ],
          });
        }, 500);
        isClick = false;
        this.$emit('handleChange', this.moveingMarkLines)
        // this.myChart.resize()
      });
      option && this.myChart.setOption(option, true);
    },
    group(array, subGroupLength) {
      let index = 0;
      let newArray = [];
      while (index < array.length) {
        newArray.push(array.slice(index, (index += subGroupLength)));
      }
      return newArray;
    },
  },
};
</script>
